package com.example.ota_ble.ble.connect


import android.annotation.SuppressLint
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothProfile
import android.os.Looper
import android.util.Log
import androidx.core.os.postDelayed
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.lifecycleScope
import com.example.ota_ble.ble.component.ota_lock
import com.example.ota_ble.ble.component.ota_lock.channel


import com.example.ota_ble.ble.data.dataBlue_uuid
import com.example.ota_ble.ble.data.dataBlue_uuid.CLIENT_CHARACTERISTIC_CONFIG_UUID
import kotlinx.coroutines.launch

import java.util.UUID
import android.os.Handler  // 正确的导入
import com.example.ota_ble.ble.ota.mcu.parseNotify
import kotlin.collections.joinToString


@SuppressLint("MissingPermission")
class bluetoothGattCallBk(manage:buletoothGattManage) : BluetoothGattCallback()  {
    var TAG = "rocjan.bluetoothGattCallBk"
    lateinit var gatt_manage:buletoothGattManage
    init{
        this.gatt_manage = manage
    }
    // 连接完成后，服务发现
    override fun onCharacteristicRead(
        gatt: BluetoothGatt,
        characteristic: BluetoothGattCharacteristic,
        value: ByteArray,
        status: Int
    ) {
        super.onCharacteristicRead(gatt, characteristic, value, status)
        Log.i(TAG, "onCharacteristicRead，服务发现${value}")
    }
    override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
        Log.i(TAG, "onConnectionStateChange，服务发现")
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            // 设备已连接，可以开始配对
            Log.d("ConnectionActivity", "设备已连接");

            // 可以开始后续的 GATT 操作，如获取服务等
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            Log.d("ConnectionActivity", "设备已断开连接");
        }

        if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
            // 连接成功，开始发现服务
            gatt?.discoverServices()
        }
    }

    //  获取服务
    override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {

        if (status == BluetoothGatt.GATT_SUCCESS) {
            // 16位 UUID 扩展为 128 位 UUID
            // OTA,ble的ota服务
            this.gatt_manage.ota_ble_service = gatt.getService(UUID.fromString(dataBlue_uuid.TELINK_SPP_DATA_OTA))
            // OTA,mcu的ota服务
            this.gatt_manage.ota_mcu_service = gatt.getService(UUID.fromString(dataBlue_uuid.SVC_DFTOTA_SERVICE_UUID))
            // 测试用的
            this.gatt_manage.test_service = gatt.getService(UUID.fromString(dataBlue_uuid.SVC_BMS_SERVICE_UUID))


            if (this.gatt_manage.ota_ble_service != null || this.gatt_manage.test_service!=null||this.gatt_manage.ota_mcu_service!=null) {
                // 获取所有特征
                // 获取ota，ble特征
                this.gatt_manage.ota_ble_characteristic = this.gatt_manage.ota_ble_service.getCharacteristic(UUID.fromString(dataBlue_uuid.TELINK_OTA_UUID_SERVICE))
                // 获取ota，mcu特征  ctrl，data
                this.gatt_manage.ota_mcu_characteristic_ctrl = this.gatt_manage.ota_mcu_service.getCharacteristic(UUID.fromString(dataBlue_uuid.SVC_DFTOTA_CHAR_CTRL_UUID))
                this.gatt_manage.ota_mcu_characteristic_data = this.gatt_manage.ota_mcu_service.getCharacteristic(UUID.fromString(dataBlue_uuid.SVC_DFTOTA_CHAR_DATA_UUID))

                this.gatt_manage.test_characteristic = this.gatt_manage.test_service.getCharacteristic(UUID.fromString(dataBlue_uuid.SVC_BMS_CHAR_PROTOBUF_UUID))



                /*监听特征的通知，比方ota，mcu - ctrl*/
//                var ota_ctrl_descriptor:BluetoothGattDescriptor = this.gatt_manage.ota_mcu_characteristic_ctrl.getDescriptor(UUID.fromString(dataBlue_uuid.CLIENT_CHARACTERISTIC_CONFIG_UUID));
//                if (ota_ctrl_descriptor != null) {
//                    ota_ctrl_descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
//                    gatt.writeDescriptor(ota_ctrl_descriptor);
//                }
                var ota_data_descriptor:BluetoothGattDescriptor = this.gatt_manage.ota_mcu_characteristic_data.getDescriptor(UUID.fromString(dataBlue_uuid.CLIENT_CHARACTERISTIC_CONFIG_UUID));
                if (ota_data_descriptor != null) {
                    ota_data_descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                    gatt.writeDescriptor(ota_data_descriptor);
                }



            } else {
                Log.i(TAG, "未找到自定义服务")
            }
        }
        else {
            Log.i(TAG, "服务发现失败，状态码：$status")
        }
    }
    override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.d(TAG, "Descriptor write successful")
            val characteristic = descriptor.characteristic

            // 获取特征的 UUID
            val characteristicUuid = characteristic.uuid
            Log.d(TAG, "Characteristic UUID: $characteristicUuid")
            when(characteristicUuid)
            {
                UUID.fromString(dataBlue_uuid.SVC_DFTOTA_CHAR_CTRL_UUID)->{
                    Handler(Looper.getMainLooper()).postDelayed({
                        val success = gatt.setCharacteristicNotification(this.gatt_manage.ota_mcu_characteristic_ctrl, true)
                        if (success) {
                            Log.d(TAG, " ctrl,Notification set success")
                        } else {
                            Log.e(TAG, "Failed to enable notification")
                        }
                    }, 500)  // 延迟500毫秒
                }
                UUID.fromString(dataBlue_uuid.SVC_DFTOTA_CHAR_DATA_UUID)->{
                    Handler(Looper.getMainLooper()).postDelayed({
                        val success = gatt.setCharacteristicNotification(this.gatt_manage.ota_mcu_characteristic_data, true)
                        if (success) {
                            Log.d(TAG, "data,Notification set success")
                        } else {
                            Log.e(TAG, "Failed to enable notification")
                        }
                    }, 100)  // 延迟500毫秒
                }
                else ->{
                    Log.d(TAG, " without set Notification ")
                }
            }



        } else {
            Log.e(TAG, "Descriptor write failed with status $status")
        }
    }

    override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.i(TAG, "Write rsp -> successful")
            channel.trySend(0).isSuccess


        } else {
            Log.i(TAG, "Write rsp ->  failed, status: $status")
            channel.trySend(-1).isSuccess
        }
    }

    // 读取数据回调
    override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            val data = characteristic.value
            Log.i(TAG, "Read successful, data: ${String(data)}")
        } else {
            Log.i(TAG, "Read failed")
        }
    }

    override fun onCharacteristicChanged(
        gatt: BluetoothGatt,
        characteristic: BluetoothGattCharacteristic
    ) {
        var uuid = characteristic.uuid
        when(uuid)
        {
            UUID.fromString(dataBlue_uuid.SVC_DFTOTA_CHAR_CTRL_UUID)-> {
                parseNotify.parse(characteristic.value)
            }
            UUID.fromString(dataBlue_uuid.SVC_DFTOTA_CHAR_DATA_UUID)-> {
                parseNotify.parse(characteristic.value)
            }
            else ->{
                Log.d(TAG, " without set Notification,data ")
            }
        }



        //Log.d(TAG, "Received data: " + data.joinToString(" "){"0x${it.toUByte().toString(16).padStart(2,'0')}"} )
    }



}